package com.gf.fund.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gf.common.bean.Page;
import com.gf.fund.dao.FundDao;
import com.gf.fund.service.FundService;

/**
 * 
 * @author zhuguifeng
 * 
 */
@Transactional
@Service("fundService")
public class FundServiceImpl implements FundService {

	@Autowired
	private FundDao fundDao;

	// 帐号初始余额
	@Value("${fund.init.money}")
	private int initMoney;

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public long initFund(long userId) {
		return fundDao.insertFund(userId, 0, 0, initMoney, "初始化");
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public double charge(long userId, double changes) {
		double total = fundDao.queryTotal(userId);
		double last = total;
		total += changes;
		fundDao.insertFund(userId, last, changes, total, "充值");

		return total;
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public double consume(long userId, double changes, String event) {
		double total = fundDao.queryTotal(userId);
		// 金额不够
		if (total < changes) {
			return -1;
		}
		double last = total;
		total -= changes;
		fundDao.insertFund(userId, last, -changes, total, event);

		return total;
	}

	@Override
	public double getTotal(long userId) {
		return fundDao.queryTotal(userId);
	}

	@Override
	public Page getFundByUserId(long userId, int pageSize, int currentPage) {
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(pageSize);
		
		page.setResults(fundDao.queryFundByUserId(userId, page));
		
		return page;
	}

	@Override
	public Page getConsumeFundByUserId(long userId, int pageSize,
			int currentPage, long startTime, long endTime) {
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(pageSize);

		page.setResults(fundDao.queryConsumeFundByUserId(userId, page,
				startTime, endTime));

		return page;
	}

	@Override
	public Page getChargeFundByUserId(long userId, int pageSize,
			int currentPage, long startTime, long endTime) {
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(pageSize);

		page.setResults(fundDao.queryChargeFundByUserId(userId, page,
				startTime, endTime));

		return page;
	}

}
